<template lang="pug">
  .CreateTreatmentAppendixModal
    Modal(
      v-model="isShowCreateTreatmentAppendixModal"
      :title="isCreate ? '新增附件' : '修改附件'"
      class-name="vertical-center-modal"
      width="480"
    )
      Form.ivu-row.has-rules-item2(ref="formCreate" :model="formCreate" :rules="rules" :label-width="100")
        FormItem.form-item.ivu-col(label="所在城市：" prop="costomerCity_arr" :class="whetherDifferentiateCities == 1 ? 'is-required':'remove-required'")
          Cascader(v-model="formCreate.costomerCity_arr" placeholder="请选择" :filterable="true" :data="areaArr" :change-on-select="true" :load-data="loadDataCity" style="width:100%;" @on-change="costomerCityChange")
        FormItem(label="附件上传：" prop="fileString")
            Input(v-model="formCreate.fileString" style="display:none")
            //- Upload(:before-upload="createHandleUpload" multiple ref="addUpload" :show-upload-list="true" action="")
            Upload(
                  ref="upload"
                  :before-upload="handleBeforeUploadBatchImport"
                  :max-size="10 * 1024"
                  :on-exceeded-size="handleMaxSizeTen"
                  :on-success="uploadSuccess"
                  multiple
                  :action="'/api/TreatmentBasicsType/TreatmentAnnexUpload?categoryName='+categoryName"
                  :show-upload-list="false"
                  :headers="headers"
                )
              Button(type="info" icon="ios-cloud-upload-outline") 点击上传
            template(v-for="(item, index) in formCreate.AttachmentName")
              .my-tag.mr-20
                .my-tag-inner {{item}}
                .img-close.ivu-icon.ivu-icon-ios-close(@click="deleteFile(index)")
      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(type="primary" @click="handleSave()" :loading="!isCanSubmit") 保存
</template>

<script>
import { Common } from '@/utils/common.js'
import dataApi from '@/api/data.js'
import { TreatmentBasicsTypeApi } from '@/api/TreatmentBasicsType.api.js'
import Cookies from 'js-cookie'
export default {
  name: 'CreateTreatmentAppendixModal',

  props: {
    areaArr: Array
  },

  watch: {
  },

  computed: {
  },

  data () {
    return {
      headers: {
        'Authorization': 'Bearer ' + Cookies.get('clientToken')
      },
      isShowCreateTreatmentAppendixModal: false,
      isCreate: true,
      categoryName: '待遇类型管理',
      whetherDifferentiateCities: 0,
      formCreate: {
        TreatmentTypeId:'',
        areaId: '',
        costomerCity_arr:[],
        file: [], // 合同附件
        fileString: '',
        AttachmentPath:[],
        AttachmentName:[],
        areaName: ''
      },
      rules: {
        costomerCity_arr: [
          { required: false, type: 'array', min: 1, message: '请选择地址', trigger: 'change' }
        ],
        fileString: [
          { required: true, type: 'string', min: 1, message: '请上传附件', trigger: 'change' }
        ],
        
      },
      arrListDown: {
        defaultRadioArr: null,
        parametertype: null,
        parameterstatus: null
      },
      isCanSubmit: true
    }
  },


  mounted () {
  },

  methods: {
    // 批量导入-上传前文件
    handleBeforeUploadBatchImport (file) {
      const models = ['.exe']
      let first = file.name.lastIndexOf(".")
      let namelength = file.name.length
      let filesuffix = file.name.substring(first, namelength)
      if (models.includes(filesuffix)) {
        this.$Message.error('文件格式不对')
        return false
      } else {
      }
    },
    // 删除文件
    deleteFile (index) {
      this.formCreate.AttachmentPath.splice(index, 1)
      this.formCreate.AttachmentName.splice(index, 1)
      if (this.formCreate.AttachmentName.length < 1) {
        this.formCreate.fileString = ''
      }
    },

    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过50M',
        duration: 50,
        closable: true
      })
    },

    // 上传合同附件
    createHandleUpload (file) {
      console.log('上传合同附件')
      console.log(file)
      console.log(this.formCreate)
      console.log(this.formCreate.fileString)
      console.log(this.formCreate.file)
      this.formCreate.fileString = file.Name
      this.formCreate.file = this.formCreate.file ? this.formCreate.file:[]
      this.formCreate.file.push(file)
      return false
    },

    // 上传成功
    uploadSuccess (res, row) {
      console.log('上传成功res: ',res)
      var fileName = res.Data.Name
      var str = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
      if (res.Success) {
        this.formCreate.fileString = res.Data.Name
        this.formCreate.AttachmentPath = this.formCreate.AttachmentPath ? this.formCreate.AttachmentPath:[]
        this.formCreate.AttachmentName = this.formCreate.AttachmentName ? this.formCreate.AttachmentName:[]
        this.formCreate.AttachmentPath.push(res.Data.Id)
        this.formCreate.AttachmentName.push(res.Data.Name)
      }
    },

    cancel () {
      this.isShowCreateTreatmentAppendixModal = false
    },

    show () {
      // this.formCreate.parameterId = id
      this.formCreate.AttachmentName = []
      this.formCreate.file = []
      this.formCreate.fileString = ''
      this.formCreate.AttachmentPath = []
      this.isShowCreateTreatmentAppendixModal = true
      this.$refs.formCreate.resetFields()
      this.isCanSubmit = true
    },

    loadDataCity (val, callback) {
      console.log('loadDataCity_____________')
      console.log(val)
      val.loading = true
      if (val.levelID === 2) {
        dataApi.getCity({ parentId: val.value }).then(res => {
          val.children = res.data.data.map(item => {
            return {
              ...item,
              label: item.name,
              value: item.id,
              children: [],
              loading: false
            }
          })
          val.loading = false
          callback()
        })
      } else  {
        dataApi.getArea({parentId: val.value}).then(res => {
          val.children = res.data.data.map(item => {
            return {...item, label: item.name, value: item.id}
          })
          val.loading = false
          callback()
        })
      }
    },

    // 所在城市选择
    costomerCityChange (value, selectedData) {
      console.log('costomerCityChange.')
      console.log(value, selectedData)
      // this.formCreate.AreaPath = value.join(',')
      console.log(this.formCreate.AreaPath)
      if (value.length > 0) {
        this.formCreate.areaId = value[value.length - 1]
        this.formCreate.areaName = selectedData[selectedData.length - 1].name
      } else {
        this.formCreate.areaId = ''
        this.formCreate.areaName = ''
      }
    },

    // 根据ID获取待遇参数
    async getModel (id) {
      let res = await TreatmentBasicsTypeApi.getTreatmentParameter({ParameterId: id})
      console.log('根据ID获取待遇参数: ', res)
      if (res.status === 200 && res.data.success) {
        var data = res.data.data.data
        Object.keys(this.formCreate).forEach(key => {
          this.formCreate[key] = data[key] + '' && data[key] + '' !== 'null' ? data[key] + '' : ''
        })
      } else {
      }
    },

    // 保存
    async handleSave () {
      this.isCanSubmit = false
      console.log('this.formCreate', this.formCreate)
      this.$refs.formCreate.validate((valid) => {
        if (valid) {
          let params = {}
          params.TreatmentTypeId = this.formCreate.TreatmentTypeId
          params.AreaId = this.formCreate.areaId
          params.AttachmentId = this.formCreate.AttachmentPath.join(',')
          TreatmentBasicsTypeApi.saveTreatmentBasicsCitys(params).then(res => {
            console.log('保存待遇参数: ', res)
            if (res.status === 200 && res.data.success) {
              this.$Message.success(res.data.message)
              this.cancel()
              this.$emit('handleSave')
              this.formCreate.AttachmentName = []
              this.formCreate.file = []
              this.formCreate.fileString = ''
              this.formCreate.AttachmentPath = []
            } else {
              this.isCanSubmit = true
              this.$Message.error({
                content: res.data.message,
                duration: 10,
                closable: true
              })
            }
          })
        } else {
          this.isCanSubmit = true
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>
